<template>
  <div class="table-box">
    <ProTable ref="proTable" title="用户列表" :columns="columns" :request-api="getTableList" :init-param="initParam"
      :data-callback="dataCallback">
      <!-- 表格 header 按钮   :tooltip-options="tooltipOptions"-->
      <template #tableHeader="scope">
        <el-button type="primary" class="standard-btn" :icon="CirclePlus" @click="openDiolg('新增', null)">
          新增用户
        </el-button>
        <el-button type="info" plain icon="Upload" @click="() => { ExcelRef.open('/staff/socialfund/importSocFee') }"
          v-hasPermi="['system:user:import']">导入</el-button>
        <el-button type="info" plain icon="Files" @click="importTemplates">模板下载</el-button>
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['system:user:export']">导出</el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <div v-if="scope.row.operationCount === 3" class="operation-wrapper-3">
          <el-button type="primary" link :icon="View" @click="openDiolg('查看', scope.row)">
            查看
          </el-button>
          <el-button type="primary" link :icon="EditPen" @click="openDiolg('编辑', scope.row)">
            编辑
          </el-button>
          <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">
            删除
          </el-button>
          <el-button type="primary" link :icon="View" @click="openDiolg('查看', scope.row)">
            查看
          </el-button>
          <el-button type="primary" link :icon="EditPen" @click="openDiolg('编辑', scope.row)">
            编辑
          </el-button>
          <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">
            删除
          </el-button>
        </div>
        <div v-else class="operation-wrapper-2">
          <el-button type="primary" link :icon="View" @click="openDiolg('查看', scope.row)">
            查看
          </el-button>
          <el-button type="primary" link :icon="EditPen" @click="openDiolg('编辑', scope.row)">
            编辑
          </el-button>
          <el-button type="primary" link :icon="View" @click="openDiolg('查看', scope.row)">
            查看
          </el-button>
          <el-button type="primary" link :icon="EditPen" @click="openDiolg('编辑', scope.row)">
            编辑
          </el-button>
        </div>
      </template>
    </ProTable>
    <ExcelUpload ref="ExcelRef" title="导入demo" type="1" :templateParams="templateParams">
    </ExcelUpload>
    <MyDiolg ref="dialogRef" />
    <!-- <div class="my-swiper">
      <carousel-3d :autoplay="true" :autoplayTimeout="3000" :perspective="35" :display="5" :animationSpeed="1000"
        :width="300" :height="250" :controlsVisible="false" :controlsHeight="60">
        <Slide :index="index" :key="index" v-for="(item, index) in imgs">
          <img :src="item" alt="Image 1" class="my-img">
        </Slide>
      </carousel-3d>
    </div> -->
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, getCurrentInstance, toRefs } from "vue";
import { Carousel3d, Slide } from 'vue3-carousel-3d';
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, tabBarProps } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import MyDiolg from "./components/Form.vue";
import {
  ColumnProps,
} from "@/components/ProTable/interface";
import {
  CirclePlus,
  Delete,
  EditPen,
  Download,
  Upload,
  View,
  Refresh,
  Files
} from "@element-plus/icons-vue";
import {
  deviceNumList,
  devTypeList,
  devOnlineStatusList,
  devUseStatusList,
  findLabel,
} from "@/utils/stata";
import { getDicts } from "@/api/system/dict/data";
import { useHandleData } from "@/hooks/useHandleData";
const proxy = getCurrentInstance()?.proxy;
const { sys_user_sex } = toRefs<any>(proxy?.useDict("sys_user_sex"));
const router = useRouter();
const ExcelRef = ref(null);
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<any>();
const imgs = ref<any>(['https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg', 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg', 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg'])
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});
const tooltipOptions = {
  'appendT-to': "app",
  'popper-class': "my-tooltip"
}
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: [
      {
        operationCount: 3,
        username: "12",
        devBrand: 0,
        sex: 0,
        userImg: [],
        createTime: "2023-10-10 10:10:10",
        longString: "舟行数日，到得武穴，已是湖北境内。这晚到了福池口，舟子泊了船，准拟过夜，俞莲舟忽听得岸上马嘶声响"
      },
      {
        operationCount: 3,
        username: "12",
        devBrand: 0,
        sex: 1,
        userImg: ['https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg'],
        createTime: "2023-10-10 10:10:10",
        longString: "舟行数日，到得武穴，已是湖北境内。这晚到了福池口，舟子泊了船，准拟过夜，俞莲舟忽听得岸上马嘶声响"
      },
      {
        operationCount: 2,
        username: "12",
        devBrand: 0,
        sex: 1,
        userImg: ['https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg', 'https://picsum.photos/400/400', 'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',],
        createTime: "2023-10-10 10:10:10",
        longString: "舟行数日，到得武穴，已是湖北境内。这晚到了福池口，舟子泊了船，准拟过夜，俞莲舟忽听得岸上马嘶声响"
      },
      {
        operationCount: 2,
        username: "12",
        devBrand: 0,
        sex: 1,
        userImg: ['https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg', 'https://picsum.photos/400/400', 'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',],
        createTime: "2023-10-10 10:10:10",
        longString: "舟行数日，到得武穴，已是湖北境内。这晚到了福池口，舟子泊了船，准拟过夜，俞莲舟忽听得岸上马嘶声响"
      },
    ],
    total: 15,
    pageNum: 1,
    pageSize: 10,
  };
};
const importTemplates = () => {
  proxy.download("/system/user/importTemplate", {}, `模板.xlsx`)

}
// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  //   let newParams = JSON.parse(JSON.stringify(params));
  //   newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  //   newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  //   delete newParams.createTime;
  //   return getUserList(newParams);
  return PromiseDel;
};
const templateParams = {
  templateName: "demo模板",
  templateUrl: "system/user/importTemplate",
  templateType: 0,
  templateObj: {}
}

// 表格配置项
const columns: any = [
  { type: "index", label: "序号", width: 80, fixed: "left" },
  //1.普通输入框
  {
    prop: "username",
    label: "用户姓名",
    search: { el: "input" },
    width: 100
  },

  //2.下拉框 自定义下拉选项类型
  {
    prop: "devBrand",
    label: "设备品牌",
    search: { el: "select" },
    enum: deviceNumList,
    render: (scope) => {
      let devBrand = findLabel(scope.row.devBrand, "deviceNumList");
      return devBrand;
    },
    width: 150
  },
  //下拉框 数据源从字典中拿
  {
    prop: "sex",
    label: "用户性别",
    search: { el: "select" },
    enum: () => {
      return getDicts("sys_user_sex");
    },
    fieldNames: { label: "dictLabel", value: "dictValue" },
    render: (scope) => {
      let sex = proxy?.selectDictLabel(sys_user_sex.value, scope.row.sex);
      return sex;
      // return <>
      //        <dict-tag options={{ sys_user_sex.value }}  value={{ scope.row.sex }} />
      // </>
    },
    width: 100
  },
  //图片
  {
    prop: "userImg",
    label: "图片(无或有)",
    render: (scope: any) => {
      if (scope.row.userImg.length === 1) {
        return (
          <el-image
            class="table-img"
            src={scope.row.userImg[0]}
            zoom-rate={1.2}
            max-scale={7}
            min-scale={0.2}
            preview-src-list={scope.row.userImg}
            fit="cover"
            preview-teleported
          />
        )
      } else if (scope.row.userImg.length === 0) {
        return '暂无图片'
      } else {

        return (
          <div class="my-swiper">
            <carousel-3d
              autoplay={true}
              autoplayTimeout={2000}
              perspective={35}
              display={5}
              animationSpeed={1000}
              width={60}
              height={60}
              controlsVisible={false}
              controlsHeight={60}
            >
              {imgs.value.map((item, index) => (
                <Slide index={index} key={index}>
                  {/* <img src={item} alt={`Image ${index + 1}`} class="my-img" /> */}
                  <el-image
                    class="table-img"
                    src={item}
                    zoom-rate={1.2}
                    max-scale={7}
                    min-scale={0.2}
                    preview-src-list={imgs.value}
                    fit="cover"
                    preview-teleported
                  />
                </Slide>
              ))}
            </carousel-3d>
          </div>
        )
        // return (
        //   <el-carousel interval="3000" type="card" class="my-carousel" indicator-position="none">
        //     {scope.row.userImg.map((item, index) => {
        //       return (
        //         <>
        //           <el-carousel-item key={index}>
        //             <el-image
        //               class="table-img"
        //               src={item}
        //               zoom-rate={1.2}
        //               max-scale={7}
        //               min-scale={0.2}
        //               preview-src-list={[item]}
        //               fit="cover"
        //               preview-teleported
        //             />
        //           </el-carousel-item>
        //         </>
        //       )
        //     })}
        //   </el-carousel>

        // )
      }
    },
    width: 150
  },
  //字典下拉
  //     {
  //   prop: 'shPositionId',
  //   label: '商会职务',
  //   search: {
  //     el: 'select'
  //   },
  //   enum: () => {
  //     return getDicts('sh_position');
  //   },
  //   fieldNames: {
  //     label: 'dictLabel',
  //     value: 'dictValue'
  //   },
  //   render: (scope: any) => {
  //     // return (
  //     //     // <dict-tag options={sh_position.value} value={scope.row.shPositionId} />

  //     // )
  //     return scope.row.postName
  //   }
  // },
  //树形下拉
  //     {
  //   prop: 'shDeptId',
  //   label: '所属组织',
  //   search: {
  //     el: 'tree-select'
  //   },
  //   fieldNames: {
  //     label: "deptName",
  //     value: "deptId",
  //   },
  //   enum: async () => {
  //     let { data } = await listDept();
  //     let list = proxy?.handleTree(data, "deptId");
  //     console.log("list", list)
  //     return {
  //       data: list
  //     };
  //   },
  //   render: (scope) => {
  //     return <span>{scope.row.shDeptName}</span>
  //   }
  // },
  // 自定义 search 显示内容
  // {
  //   prop: 'vipPoint',
  //   label: '积分',
  //   width: 120,
  //   search: {
  //     // 自定义 search 显示内容
  //     render: ({ searchParam }) => {
  //       console.log("自定义 search 显示内容", searchParam)
  //       return (
  //         <div class="flx-center">
  //           <el-input vModel_trim={searchParam.vipPointBefore} placeholder="最小积分" />
  //           <span class="mr10 ml10">-</span>
  //           <el-input vModel_trim={searchParam.vipPointAfter} placeholder="最大积分" />
  //         </div>
  //       );
  //     }
  //   }
  // },
  {
    prop: "longString",
    label: "状态",
    render: (scope) => {
      if (scope.row.sex == 0) {
        return <el-tag type="primary">待审核</el-tag>
      } else if (scope.row.sex == 1) {
        return <el-tag type="success">审核中</el-tag>
      } else if (scope.row.sex == 2) {
        return <el-tag type="success">审核通过</el-tag>
      } else if (scope.row.sex == 3) {
        return <el-tag type="danger">审核拒绝</el-tag>
      }
      else {
        return <el-tag type="primary">无需审核</el-tag>
      }
    },
    enum: [
      {
        label: '待审核',
        value: 0
      },
      {
        label: '审核中',
        value: 1
      },
      {
        label: '审核通过',
        value: 2
      },
      {
        label: '审核拒绝',
        value: 3
      },
      {
        label: '无需审核',
        value: 4
      }
    ],
  },
  {
    prop: "longString",
    label: "长文字多行",
    width: 300,
    search: { el: "input" },
    showOverflowTooltip: false,
    render: (scope: any) => {
      return <>
        <el-tooltip
          effect="dark"
          content={scope.row.longString}
          placement="top"
        >
          <div class="table-ellipsis">
            {scope.row.longString}
          </div>
        </el-tooltip>

      </>
    },
  },

  {
    prop: "longString",
    label: "长文字单行",
    search: { el: "input" },
    showOverflowTooltip: true,
  }, {
    prop: "longString",
    label: "长文字单行",
    search: { el: "input" },
    showOverflowTooltip: true,
  }, {
    prop: "longString",
    label: "长文字单行",
    search: { el: "input" },
    showOverflowTooltip: true,
  }, {
    prop: "longString",
    label: "长文字单行",
    search: { el: "input" },
    showOverflowTooltip: true,
  },
  {
    prop: "longString",
    label: "长文字单行",
    search: { el: "input" },
    showOverflowTooltip: true,
  },
  {
    prop: "longString",
    label: "长文字单行",
    search: { el: "input" },
    showOverflowTooltip: true,
  },
  {
    prop: "longString",
    label: "长文字单行",
    search: { el: "input" },
    showOverflowTooltip: true,
  },
  {
    prop: "longString",
    label: "长文字单行",
    search: { el: "input" },
    showOverflowTooltip: true,
  },
  // 日期连选
  {
    prop: "createTime",
    label: "创建时间",
    width: 180,
    search: {
      el: "date-picker",
      span: 2,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" },
      //   defaultValue: ["2022-11-12 11:35:00", "2022-12-12 11:35:00"],
    },
  },
  { prop: "operation", label: "操作", fixed: "right", width: 240 },
];

// 删除用户信息
const deleteAccount = async (params: any) => {
  await useHandleData(PromiseDel, { id: [params.id] }, '是否删除编号为' + 1 + '的数据');
  proTable.value?.getTableList();
};
//模拟 调用接口
const PromiseDel = () => new Promise((resolve, reject) => resolve(true))

/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/user/export", {

  }, `user_${new Date().getTime()}.xlsx`);
};
// 打开 drawer(新增、查看、编辑)
const dialogRef = ref<InstanceType<typeof MyDiolg> | null>(null);
const openDiolg = (title: string, row: any) => {
  const params = {
    title,
    isView: title === "查看",
    rowData: { ...row },
    api: title === "新增" ? () => Promise.resolve(true) : title === "编辑" ? () => Promise.resolve(true) : undefined,
    getTableList: proTable.value?.getTableList,
  };
  dialogRef.value?.acceptParams(params);
};
</script>
<style lang="scss" scoped>
// .my-swiper {
//   margin-top: 10px;
//   height: 120px;
//   width: 260px;
//   display: flex;
//   justify-content: center;
//   align-items: center;
//   background-color: aqua;

//   .my-img {
//     width: 100%;
//     height: 100%;
//     object-fit: cover;
//   }

//   .ceshi {
//     height: 120px;
//     width: 120px;
//     background-color: red;
//   }
// }
.my-swiper {
  margin-top: 10px;
  height: 80px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

:deep(.el-carousel__container) {
  height: 70px !important;
}

.my-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.table-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.my-tooltip {
  width: 220px !important;
}
</style>